/*
 * Copyright 2007 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja.spi.data;

import java.util.List;

import net.datajanitor.baja.data.FileInfo;

import org.jdom.Element;

public class FileInfoTreeBuilder {
    private void buildFromXml(Element element, FileInfoTree tree) {
        buildFromXml(element, tree.getRoot(), tree); 
    }
    
    private void buildFromXml(Element element, FileInfo parent, FileInfoTree tree) {
        Element filesRoot = element.getChild("files");
        if (filesRoot != null) {
            @SuppressWarnings({"unchecked"})
            List<Element> files = (List<Element>) filesRoot.getChildren("file");
            for (Element file : files) {
                tree.addFileInfo(parent, new FileInfo(Integer.parseInt(file.getAttributeValue("id")), file.getAttributeValue("file_name"), false, tree)); 
            }
        }
        
        Element foldersRoot = element.getChild("folders");
        if (foldersRoot != null) {
            @SuppressWarnings({"unchecked"})
            List<Element> folders = (List<Element>) foldersRoot.getChildren("folder");
   
            for (Element folder : folders) {
                FileInfo dirInfo = new FileInfo(Integer.parseInt(folder.getAttributeValue("id")), folder.getAttributeValue("name"), true, tree);
                tree.addFileInfo(parent, dirInfo);
                buildFromXml(folder, dirInfo, tree);        
            }
        }
    }
     
    public FileInfoTree buildFromXml(Element element) {
        Element folder = element.getChild("folder");
        FileInfoTree tree = FileInfoTree.newFileInfoTree(Integer.parseInt(folder.getAttributeValue("id")), folder.getAttributeValue("name"));
        
        buildFromXml(folder, tree);
        return tree;
    }
}
